#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    ,flagVideo(0)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
    this->setWindowTitle("远程小车控制软件 v1.0");
    this->setWindowIcon(QIcon(":/new/prefix1/title.png"));

    //初始化TCP客户端
    myTcp = new QTcpSocket(this);   //实例化tcpClient
    myTcp->abort();                 //取消原有连接

    connect(myTcp, SIGNAL(readyRead()), this, SLOT(onTcpReadData()));
    connect(myTcp, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(onTcpError(QAbstractSocket::SocketError)));

    videoThread  = new QThread(this);
    myVedio = new Video();
    myVedio->setShowVedioLab(ui->videoWidget->getImgLab());     //将显示图片的lab地址传入接收线程
    myVedio->moveToThread(videoThread);
    videoThread->start();
    // 鼠标位置控制信号
    connect(ui->videoWidget,SIGNAL(sPosChanged(QPoint)) ,this,SLOT(on_mouseMove(QPoint)));
    carState.setSensitive((uchar)ui->spinBox_x->value(),(uchar)ui->spinBox_y->value());
    carState.setTcp(myTcp);
    this->clearFocus();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_connectTcp_clicked()
{
    if(myTcp->state() != QAbstractSocket::ConnectedState)
    {
        QString ipStr = ui->lineEdit_ip->text();
        quint16 port = ui->lineEdit_tcpPort->text().toUInt();
        myTcp->abort();
        myTcp->connectToHost(ipStr, port);
        ui->pushButton_connectTcp->setText("连接中...");
        ui->pushButton_connectTcp->setEnabled(false);
        this->setEnabled(0);
        qApp->processEvents();
        if (myTcp->waitForConnected(3000))  // 连接成功
        {
            carState.setControlFlag(true);
            ui->pushButton_connectTcp->setText("断开");
            ui->groupBox_udpSet->setEnabled(false);
            ui->groupBox_controlSet->setEnabled(false);
        }
        else
        {
            carState.setControlFlag(false);
            ui->pushButton_connectTcp->setText("连接");
            ui->groupBox_udpSet->setEnabled(true);
            ui->groupBox_controlSet->setEnabled(true);
        }
        this->setEnabled(1);
    }
    else
    {
        myTcp->disconnectFromHost();
        ui->pushButton_connectTcp->setText("断开中...");
        ui->pushButton_connectTcp->setEnabled(false);
        if (myTcp->state() == QAbstractSocket::UnconnectedState \
               || myTcp->waitForDisconnected(1000))  //已断开连接
        {
            carState.setControlFlag(false);
            ui->pushButton_connectTcp->setText("连接");
            ui->groupBox_udpSet->setEnabled(true);
            ui->groupBox_controlSet->setEnabled(true);
        }
        else
        {
            carState.setControlFlag(true);
            ui->pushButton_connectTcp->setText("断开");
        }
    }
    ui->pushButton_connectTcp->setEnabled(true);
}

void MainWindow::onTcpReadData()
{
    QByteArray buffer = myTcp->readAll();
    if(!buffer.isEmpty())
    {

    }
}

qint64 MainWindow::tcpSend(QByteArray data)
{
    return myTcp->write(data);
}
qint64 MainWindow::tcpSend(QString data)
{
    return myTcp->write(data.toLatin1());
}
void MainWindow::onTcpError(QAbstractSocket::SocketError)
{

}

void MainWindow::on_pushButton_clicked()
{
    quint64 port = ui->lineEdit_udpPort->text().toUInt();
    quint16 portLast = myVedio->setUdpPort(port);
    ui->lineEdit_udpPort->setText(QString::number(portLast));
}

void MainWindow::on_spinBox_valueChanged(int arg1)
{
    ui->videoWidget->setMouseAcute(arg1);       //修改灵敏度
}

bool mousePressFlag = 0;
QPoint lastPos;
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    mousePressFlag = 1;
    lastPos = cursor().pos();
    if(ui->videoWidget->geometry().contains(this->mapFromGlobal(QCursor::pos())))       //判断光标是否在移动显示控制窗口内
    {
        if(myTcp->state() != QAbstractSocket::ConnectedState)
            return;
        ui->videoWidget->setMouseTracking(true);    //设置鼠标移动时刻激活事件
        QPoint center(ui->videoWidget->x() + ui->videoWidget->width() / 2,
                      ui->videoWidget->y() + ui->videoWidget->height() / 2);
        center = this->mapToGlobal(center);         //将控件中心位置映射为桌面位置
        QCursor::setPos(center);                    //设置鼠标位于显示窗口中心
        this->setCursor(Qt::BlankCursor);           //隐藏鼠标光标
    }
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(!mousePressFlag) return;
    QPoint currentPos = cursor().pos();
    QPoint movePos = currentPos - lastPos;
    lastPos = currentPos;
    this->move(this->pos()+movePos);
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    mousePressFlag = 0;
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    Qt::Key pressKey = (Qt::Key)event->key();
    qDebug()<<"key pressed: "<<event;
    if(pressKey == Qt::Key_Escape)                  //点击ESC退出鼠标移动控制
    {
        ui->videoWidget->setMouseTracking(false);       //取消鼠标移动时刻激活事件（只有按住鼠标键移动才有效）
        this->setCursor(Qt::ArrowCursor);               //显示鼠标光标
    }
    carState.setPress(pressKey);
}

void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
    Qt::Key pressKey = (Qt::Key)event->key();
    carState.setRelase(pressKey);
}

void MainWindow::on_mouseMove(QPoint pos)
{
    carState.servoPosChanged(pos.x(),pos.y());
}



void MainWindow::on_spinBox_x_valueChanged(int arg1)
{
    carState.setSensitive((uchar)ui->spinBox_x->value(),(uchar)ui->spinBox_y->value());
}

void MainWindow::on_spinBox_y_valueChanged(int arg1)
{
    carState.setSensitive((uchar)ui->spinBox_x->value(),(uchar)ui->spinBox_y->value());
}

void MainWindow::on_pushButton_quit_clicked()
{
    close();
}

void MainWindow::on_pushButton_max_clicked()
{
    if(windowState() != Qt::WindowMaximized)
        setWindowState(Qt::WindowMaximized);
    else
        setWindowState(Qt::WindowNoState);
}


void MainWindow::on_pushButton_min_clicked()
{
    setWindowState(Qt::WindowMinimized);
}

void MainWindow::on_pushButton_about_clicked()
{
    QUdpSocket udpBuff;
    QImage *buff;
    buff = new QImage((":/new/prefix1/initPicture.jpg"));
    qDebug()<<"img size:"<<buff->byteCount()<<"   img size:"<<buff->size()<<"   img format:"<<buff->format();
    myVedio->imgSend(buff,&udpBuff,"127.0.0.1",5688);
    delete buff;
}
